//
//  GroupEditViewController.m
//  SocialChair
//
//  Created by Kelly Heffner Wilkerson on 9/27/10.
//  Copyright 2010 Decipher Media, LLC. All rights reserved.
//

#import "GroupEditViewController.h"


@implementation GroupEditViewController


#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/
-(void)refreshGroupImage {
	UIImage *groupPic = [theLists getGroupPictureForIndex:groupID];
	if (groupPic != nil) {
		[personImageButton setImage:groupPic forState:UIControlStateNormal];
	} else {
		[personImageButton setTitle:@"Add a Photo" forState:UIControlStateNormal];
	}

}

-(void)refreshButtons {
	composeButton.enabled = [[theLists getListAtIndex:groupID] count] > 0;
}

-(void)setupWithGroupID:(int)num fromList:(TextLists*)list{
	groupID = num;
	theLists = list;
	
	self.title = nameField.text = [theLists getListNameAtIndex:num];
	[self refreshGroupImage];
	[self refreshButtons];
}

+(GroupEditViewController*)newGroupEditWithGroupNum:(int)groupNum fromList:(TextLists*)list {
	
	NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"GroupEdit" owner:self options:nil];
	GroupEditViewController *retVal = (GroupEditViewController *)[nib objectAtIndex:0];
	[retVal setupWithGroupID:groupNum fromList:list];
	return retVal;
}

#pragma mark -
#pragma mark View lifecycle

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [[theLists getListAtIndex:groupID] count] + 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	
	if (indexPath.row == 0) {
		cell.textLabel.text = @"Add new contact...";
	} else {
    
		// Configure the cell...
		NSLog(@"thelists: %@", theLists);
		int index = indexPath.row - 1;
		
		cell.textLabel.text = [theLists group:groupID memberNameAtIndex:index];
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@: %@", 
									 [theLists group:groupID memberLabelAtIndex:index], 
									 [theLists group:groupID memberNumberAtIndex:index]];
    }
    return cell;
}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
	return indexPath.row != 0;
}




// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		[theLists deletePersonAtListIndex:groupID withPersonIndex:indexPath.row - 1];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		[self refreshButtons];
    }   
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if (indexPath.row == 0) {
		ABPeoplePickerNavigationController *picker = [[[ABPeoplePickerNavigationController alloc] init] autorelease];
		picker.peoplePickerDelegate = self;
		picker.displayedProperties = [NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonPhoneProperty]];
		
		[self presentModalViewController:picker animated:YES];
	}
	
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person {
	return YES;
}

#pragma mark This is where the contact is added
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier{
	
	CFStringRef name = ABRecordCopyCompositeName(person); 
	
	ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
	NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);
	
	NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phoneProperty, identifier));

	[theLists addPersonAtListIndex:groupID withName:(NSString*)name number:phone andLabel:label];
	
	[self dismissModalViewControllerAnimated:YES];
	[contactsTable reloadData];
	[self refreshButtons];
    return NO;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark --
#pragma mark Make the keyboard not so damn annoying

-(void)rewriteName {
	NSString *newName = [nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	if ([newName length] > 0 && ![newName isEqualToString:[theLists getListNameAtIndex:groupID]]) {
		[theLists setListName:newName atIndex:groupID];
	}
	self.title = nameField.text = [theLists getListNameAtIndex:groupID];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	[textField resignFirstResponder];
	[self rewriteName];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	[nameField resignFirstResponder];
	//[self rewriteName];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[nameField resignFirstResponder];
	return YES;
}

#pragma mark -
#pragma mark button handlers

-(IBAction)composePressed {
	[nameField resignFirstResponder];
	TextComposeViewController *composeVC = [TextComposeViewController newGroupEditWithGroupNum:groupID fromList:theLists];
	[self.navigationController pushViewController:composeVC animated:YES];
}

#pragma mark -
#pragma mark image picking

- (IBAction)selectPhoto { 
	
	BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
	BOOL isPhotoLibAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
	
	UIActionSheet *photoChoices;
	if (isCameraAvailable && isPhotoLibAvailable) {
		photoChoices = [[[UIActionSheet alloc] initWithTitle:nil
												   delegate:self 
										  cancelButtonTitle:@"Cancel"
									 destructiveButtonTitle:nil
										   otherButtonTitles:@"From Camera", @"From Photo Album", nil] autorelease];
		[photoChoices showInView:self.view];
	} else if (isCameraAvailable) {
		[self selectPhotoFromPickerWithCamera:YES];
	} else if (isPhotoLibAvailable) {
		[self selectPhotoFromPickerWithCamera:NO];
	} else { // no choices available
		photoChoices = [[[UIActionSheet alloc] initWithTitle:@"We currently cannot find a camera or photo library on your device."
													delegate:self 
										   cancelButtonTitle:@"Cancel"
									  destructiveButtonTitle:nil
										   otherButtonTitles:nil] autorelease];
		[photoChoices showInView:self.view];
	}
	
}

// we want default behavior
//- (void)actionSheetCancel:(UIActionSheet *)actionSheet { }


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	[self selectPhotoFromPickerWithCamera:buttonIndex == 0];
}

-(IBAction) selectPhotoFromPickerWithCamera:(BOOL) camera{
	
	UIImagePickerController *imagePicker = [theLists getPicker];
	imagePicker.allowsEditing = YES;
	imagePicker.delegate = self;
	imagePicker.sourceType = camera? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
	
	[self presentModalViewController:imagePicker animated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
	if (image == nil) {
		image = [info objectForKey:UIImagePickerControllerOriginalImage];
	}

	[theLists addGroupPicture:image forIndex:groupID];
	[self refreshGroupImage];
	
	[self dismissModalViewControllerAnimated:YES];
	
	//We need a timer here to let the overlay show, and then continue processing
//	[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(continueProcessing:) userInfo:nil repeats:NO];
}

/*
// this is where the working-set is the largest, right where we need to work with the image pickers huge image
-(void)continueProcessing:(NSTimer*)theTimer {
    // right now we're always working f
	if(fromCamera) {
		// we need the section of the original photo, cropped and scaled to be what the guides had.
		
		// scale down the image using the ratio of the camera screen width (320) divided
		// by the width of the huge image given back by the camera
		float scale = CAM_VIEWPORT_WIDTH/self.workingImage.size.width;
		
		// this new image is CAM_WIDTH by CAM_HEIGHT, within the location
		// of that crop box
		self.workingImage = [AlignmentViewController imageWithImage:self.workingImage 
													   cropWithRect:CGRectMake(CAM_X,
																			   CAM_Y,
																			   CAM_WIDTH,
																			   CAM_HEIGHT)
														   andScale:scale];
		
		//now, we line up that image within the scoll view so that it matches to 
		// the guides on the camera screen
		initialScrollOffset = CGPointMake(CAM_SCROLL_OFFSET_X, CAM_SCROLL_OFFSET_Y);
	} else { // otherwise we're working from saved image 		
		UIImage *theImage = self.workingImage;
		
		NSLog(@"the image size is %f,%f", theImage.size.width, theImage.size.height);
		// Apple guidelines suggest against using UIImages greater than 1024x1024
		float newWidth, newHeight;
		
		if(theImage.size.width > theImage.size.height) {
			newWidth = fmin(MAX_DIM, theImage.size.width);
			newHeight = newWidth / theImage.size.width * theImage.size.height;
		} else {
			newHeight = fmin(MAX_DIM, theImage.size.height);
			newWidth = newHeight / theImage.size.height * theImage.size.width;
		}
		
		//self.workingImage = [AlignmentViewController imageWithImage:theImage scaledToSize:CGSizeMake(newWidth, newHeight)];
		self.workingImage = theImage;
		
		//offset by the pixels we're cutting off from the 320x320 image so that
		//if someone loads an image saved from here, it's aligned properly
		initialScrollOffset = CGPointMake(LOAD_SCROLL_OFFSET_X, LOAD_SCROLL_OFFSET_Y);
	}
	
	
	[appDelegate removeOverlayOfView:processingImage];
	[appDelegate showThisView:self];
}
*/

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[self dismissModalViewControllerAnimated:YES];
}



@end

